package com.shop.loan.util;

import cn.hutool.core.date.DateUtil;
import com.shop.loan.model.entity.SettingByMybatis;
import com.shop.loan.oss.UCloudUtil;
import com.shop.loan.service.SettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class BackupUtil {


    @Resource
    UCloudUtil uCloudUtil;

    @Resource
    SettingService settingService;

    @Value("${spring.datasource.username}")
    private String user_name;//数据库用户名

    @Value("${spring.datasource.password}")
    private String password;//数据库密码

    private String docker_sql_path = "/usr/bin/mysqldump";

    private String dbName = "shop_loan";

    private String backup_path = "/data/dump";//存放备份文件的路径


    public void backupRun() {
        String filePath = backup_path + "/" + dbName + ".sql";
        String stmt = "docker exec mysql sh -c 'exec " + docker_sql_path + " -u " + user_name + " -p\"" + password + "\"" +
                " -q -R --databases " + dbName + "' > " + filePath;
        List<String> commands = new ArrayList<>();
        commands.add("mkdir -p " + backup_path);
        commands.add(stmt);
        ConsoleUtil.executeNewFlow(commands);
    }

    @Async
    public void uploadDbFile() {
        String prefix = "";
        SettingByMybatis setting = settingService.getSetting();
        if (setting != null && setting.getPrefix() != null) {
            prefix = setting.getPrefix();
        }
        String filePath = backup_path + "/" + dbName + ".sql";
        String fileName = prefix + "-loan-" + DateUtil.today() + "---" + DateUtil.thisHour(true);
        uCloudUtil.putFile(filePath, fileName);
    }


}
